import Koa from "koa";
import logger from "koa-logger";
import json from "koa-json";
import onerror from "koa-onerror";
import bodyparser from "koa-bodyparser";
import KoaStatic from "koa-static";
import path from "path";
import { uniAuth, jwtAuth } from "./lib/uni_auth";
import { getConfig } from "./config";
import { router as api } from "./router/api";
import { ApolloServer } from "apollo-server-koa";
import { typeDefs, resolvers } from "./schema";
const app = new Koa();

// logger
app.use(logger());

// error handler
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = {
      success: false,
      message: err.message,
    };
    if (ctx.status === 500) {
      ctx.body.message = "server internal error, try again later";
      console.log(err);
    }
  }
});
onerror(app);

// parser
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(json());

// static
app.use(KoaStatic(path.resolve(__dirname, "../frontend/dist")));

// auth
// uniAuth(app, getConfig());
// app.use(jwtAuth("secret"));

// apps
app.use(api.routes());

const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app });

export default app;
